import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { BadRequestException } from '@nestjs/common';

/**
 * 自定义文件上传拦截器，封装了文件存储、限制和过滤逻辑
 * @param fieldName 上传文件的字段名称
 */
export function CustomFileUploadInterceptor(fieldName: string) {
  return FileInterceptor(fieldName, {
    storage: diskStorage({
      destination: './uploads', // 文件保存路径
      filename: (req, file, callback) => {
        // 为避免文件名重复，可以加上时间戳
        const filename = `${Date.now()}-${file.originalname}`;
        callback(null, filename);
      },
    }),
    limits: {
      fileSize: 1024 * 1024 * 5, // 限制文件大小为5MB
    },
    fileFilter: (req, file, callback) => {
      if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
        callback(null, true);
      } else {
        callback(new BadRequestException('只支持JPEG和PNG格式的图片'), false);
      }
    },
  });
}
